const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    deviceId: null,
    snNumber: null,
    deviceList: [],
    show: false
  },

  /**
   * 添加设备
   */
  toAddDevice() {
    wx.navigateTo({
      url: "/pages/management/add-device/index"
    });
  },
  getData() {
    let params = {
      companyId: app.globalData.userInfo.companyData.companyId,
      firstTheDeviceId: 15,
      secondTheDeviceId: 83
    };
    wx.$apis.getListFacilitiesByCondition(params).then((res) => {
      if (res.data) {
        const { records } = res.data;
        this.setData({
          deviceList: records.map((item) => {
            return {
              ...item,
              nowTime: wx.$dayjs().format("YYYY-MM-DD HH:mm:ss")
            };
          })
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    this.getData();
  },
  // 设备列表长按
  handleLongPress(e) {
    const { id, sn } = e.currentTarget.dataset;
    this.setData({
      deviceId: id,
      snNumber: sn
    });
    this.showPopup();
  },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false, deviceId: null, snNumber: null });
  },
  // 删除设备，删除亦是解绑
  onDelete() {
    let _this = this;
    let params = {
      id: this.data.deviceId,
      snNumber: this.data.snNumber
    };

    wx.showModal({
      title: "提示",
      content: "确认删除设备吗？",
      success: function (res) {
        if (res.cancel) {
          _this.onClose();
        } else {
          wx.$apis
            .unBindDevice(params)
            .then((res) => {
              wx.showToast({
                title: "删除成功"
              });
              _this.onClose();
              _this.getData();
            })
            .catch((err) => {
              if (err.code === 500) {
                wx.showToast({
                  title: err.message,
                  icon: "none"
                });
              } else {
                wx.showToast({
                  title: "删除失败",
                  icon: "none"
                });
              }
            });
        }
      }
    });
  }
});
